#include "chatdialog.h"
#include "ui_chatdialog.h"

ChatDialog::ChatDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ChatDialog)
{
    ui->setupUi(this);

    ui->btnSend->setDisabled(true);
    //创建套接字
    m_sock = new QTcpSocket(this);

    connect(m_sock,&QTcpSocket::connected,this,&ChatDialog::connectSuccess);
    connect(m_sock,&QTcpSocket::readyRead,this,&ChatDialog::recvMsg);
    connect(m_sock,QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error),this,&ChatDialog::errorHandle);

    ui->edtRecord->appendPlainText("[系统]正在连接服务器,请稍后....\n\n");


    //连接服务器
    m_sock->connectToHost("60.205.186.62",1966);



}



ChatDialog::~ChatDialog()
{
    delete ui;
}

void ChatDialog::connectSuccess()
{
     ui->edtRecord->appendPlainText("[系统]连接服务器成功！\n\n");
     ui->btnSend->setEnabled(true);
}

void ChatDialog::errorHandle()
{
    ui->edtRecord->appendPlainText("[系统]连接服务器失败！\n\n");
    ui->btnSend->setEnabled(false);
}

void ChatDialog::recvMsg()
{
    QByteArray data = m_sock->readAll();

    ui->edtRecord->appendPlainText(QString::fromUtf8(data) + "\n\n");
}


void ChatDialog::on_btnSend_clicked()
{
    QString msg = ui->edtMsg->toPlainText();

    m_sock->write(msg.toUtf8());

    ui->edtMsg->clear();

}
